<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.2">


  <link rel="apple-touch-icon" sizes="180x180" href="/page/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/page/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/page/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/page/images/logo.svg" color="#222">

<link rel="stylesheet" href="/page/css/main.css">



<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.4/css/all.min.css" integrity="sha256-mUZM63G8m73Mcidfrv5E+Y61y7a12O5mW4ezU3bxqW4=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"assd12138.gitee.io","root":"/page/","images":"/page/images","scheme":"Gemini","darkmode":false,"version":"8.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":false,"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/page/search.json","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}}</script><script src="/page/js/config.js"></script>
<meta name="description" content="Vue响应式的基础原理">
<meta property="og:type" content="article">
<meta property="og:title" content="Vue响应式的基础原理">
<meta property="og:url" content="https://assd12138.gitee.io/page/2021/11/14/Vue%E5%93%8D%E5%BA%94%E5%BC%8F%E7%9A%84%E5%9F%BA%E7%A1%80%E5%8E%9F%E7%90%86/index.html">
<meta property="og:site_name" content="爱爱爱呵风他">
<meta property="og:description" content="Vue响应式的基础原理">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-11-14T01:19:23.000Z">
<meta property="article:modified_time" content="2022-05-09T03:18:13.062Z">
<meta property="article:author" content="爱爱爱呵风他">
<meta property="article:tag" content="Vue">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="https://assd12138.gitee.io/page/2021/11/14/Vue%E5%93%8D%E5%BA%94%E5%BC%8F%E7%9A%84%E5%9F%BA%E7%A1%80%E5%8E%9F%E7%90%86/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"https://assd12138.gitee.io/page/2021/11/14/Vue%E5%93%8D%E5%BA%94%E5%BC%8F%E7%9A%84%E5%9F%BA%E7%A1%80%E5%8E%9F%E7%90%86/","path":"2021/11/14/Vue响应式的基础原理/","title":"Vue响应式的基础原理"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>Vue响应式的基础原理 | 爱爱爱呵风他</title>
  




  <noscript>
    <link rel="stylesheet" href="/page/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/page/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">爱爱爱呵风他</h1>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu">
        <li class="menu-item menu-item-home"><a href="/page/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li>
        <li class="menu-item menu-item-tags"><a href="/page/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a></li>
        <li class="menu-item menu-item-archives"><a href="/page/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%8B%A6%E6%88%AA%E6%93%8D%E4%BD%9C%E7%9A%84Object-defineProperty"><span class="nav-number">1.</span> <span class="nav-text">拦截操作的Object.defineProperty()</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%AE%9E%E7%8E%B0%E6%89%8B%E5%8A%A8%E5%BC%8F%E7%9A%84%E4%BE%9D%E8%B5%96%E6%94%B6%E9%9B%86%E6%A8%A1%E5%BC%8F"><span class="nav-number">2.</span> <span class="nav-text">实现手动式的依赖收集模式</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BB%80%E4%B9%88%E6%98%AF%E4%BE%9D%E8%B5%96"><span class="nav-number">2.1.</span> <span class="nav-text">什么是依赖</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%8F%AF%E4%BC%98%E5%8C%96%E7%82%B9"><span class="nav-number">2.2.</span> <span class="nav-text">可优化点</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%A7%A3%E5%86%B3%E5%86%99%E4%B8%A4%E6%AC%A1%E7%9A%84%E9%97%AE%E9%A2%98"><span class="nav-number">2.3.</span> <span class="nav-text">解决写两次的问题</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E7%AE%80%E5%8D%95%E7%9A%84autorun"><span class="nav-number">2.3.1.</span> <span class="nav-text">简单的autorun</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E4%BD%BF%E7%94%A8Dep%E5%B0%86effect%E5%87%BD%E6%95%B0%E6%94%B6%E9%9B%86%E8%B5%B7%E6%9D%A5"><span class="nav-number">2.3.2.</span> <span class="nav-text">使用Dep将effect函数收集起来</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%A7%A3%E5%86%B3%E9%9C%80%E8%A6%81%E6%89%8B%E5%8A%A8%E8%B0%83%E7%94%A8%E7%9A%84%E9%97%AE%E9%A2%98"><span class="nav-number">2.4.</span> <span class="nav-text">解决需要手动调用的问题</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%BF%9B%E4%B8%80%E6%AD%A5%E4%BD%BF%E5%85%B6%E6%9B%B4%E5%83%8FVue"><span class="nav-number">2.5.</span> <span class="nav-text">进一步使其更像Vue</span></a></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="爱爱爱呵风他"
      src="https://s1.ax1x.com/2020/08/26/dWnF58.jpg">
  <p class="site-author-name" itemprop="name">爱爱爱呵风他</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/page/archives/">
          <span class="site-state-item-count">24</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/page/tags/">
        <span class="site-state-item-count">11</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="cc-license site-overview-item animated" itemprop="license">
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/zh-cn" class="cc-opacity" rel="noopener" target="_blank"><img src="https://cdn.jsdelivr.net/npm/@creativecommons/vocabulary@2020.11.3/assets/license_badges/small/by_nc_sa.svg" alt="Creative Commons"></a>
  </div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://assd12138.gitee.io/page/2021/11/14/Vue%E5%93%8D%E5%BA%94%E5%BC%8F%E7%9A%84%E5%9F%BA%E7%A1%80%E5%8E%9F%E7%90%86/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="https://s1.ax1x.com/2020/08/26/dWnF58.jpg">
      <meta itemprop="name" content="爱爱爱呵风他">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="爱爱爱呵风他">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Vue响应式的基础原理
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2021-11-14 09:19:23" itemprop="dateCreated datePublished" datetime="2021-11-14T09:19:23+08:00">2021-11-14</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">更新于</span>
        <time title="修改时间：2022-05-09 11:18:13" itemprop="dateModified" datetime="2022-05-09T11:18:13+08:00">2022-05-09</time>
      </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <p>Vue响应式的基础原理</p>
<span id="more"></span>

<h2 id="拦截操作的Object-defineProperty"><a href="#拦截操作的Object-defineProperty" class="headerlink" title="拦截操作的Object.defineProperty()"></a>拦截操作的<code>Object.defineProperty()</code></h2><p>使用<code>Object.defineProperty()</code>可以设置一个对象的成员的<code>getter</code>和<code>setter</code>以此来拦截对于新成员的操作，目标是实现一个<code>observe</code>函数，能够为一个对象的所有属性设置<code>getter</code>和<code>setter</code></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">observe</span>(<span class="params">obj</span>)&#123;</span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">const</span> key <span class="keyword">in</span> obj)&#123;</span><br><span class="line">        <span class="comment">// 初始化代理对象，对于obj[key]的后续读写其实都是对于这个代理对象的操作</span></span><br><span class="line">        <span class="keyword">let</span> val = obj[key]</span><br><span class="line">        <span class="title class_">Object</span>.<span class="title function_">defineProperty</span>(obj,key,&#123;</span><br><span class="line">            <span class="title function_">get</span>(<span class="params"></span>)&#123;</span><br><span class="line">                <span class="keyword">return</span> val</span><br><span class="line">            &#125;,</span><br><span class="line">            <span class="title function_">set</span>(<span class="params">newVal</span>)&#123;</span><br><span class="line">                val = newVal</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="实现手动式的依赖收集模式"><a href="#实现手动式的依赖收集模式" class="headerlink" title="实现手动式的依赖收集模式"></a>实现手动式的依赖收集模式</h2><h3 id="什么是依赖"><a href="#什么是依赖" class="headerlink" title="什么是依赖"></a>什么是依赖</h3><p>将一个对象上所有的操作会牵连到的所有其他必须再运算的的操作，可以称之为<code>副作用</code>，例如</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> a = <span class="number">1</span></span><br><span class="line"><span class="keyword">let</span> b = a*<span class="number">3</span></span><br><span class="line">a = <span class="number">2</span></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(b) <span class="comment">// 3</span></span><br></pre></td></tr></table></figure>

<p>上面这个b在a更改后，不能保持其与a的3倍的同步，为了保持这个同步，需要再次计算一次</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> a = <span class="number">1</span></span><br><span class="line"><span class="keyword">let</span> b = a*<span class="number">3</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">effect</span>(<span class="params"></span>)&#123;</span><br><span class="line">    b = a*<span class="number">3</span></span><br><span class="line">&#125;</span><br><span class="line">a = <span class="number">2</span></span><br><span class="line"><span class="title function_">effect</span>()</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(b) <span class="comment">// 6</span></span><br></pre></td></tr></table></figure>

<p>上面的这个<code>effect</code>函数就是一个副作用，每次我们调用完给<code>a</code>设置值以后，都必须手动调用<code>effect()</code>来再次的进行运算，因此这个副作用也就被称作为一个依赖。</p>
<h3 id="可优化点"><a href="#可优化点" class="headerlink" title="可优化点"></a>可优化点</h3><p>上面写法的不良之处有两点，</p>
<ol>
<li><code>effect</code>中的<code>a*3</code>写了两次，初始化中写了一次，又在定义副作用时写了一次。</li>
<li>副作用需要手动运行，每次对a进行更改后，都需要手动的运行<code>effect()</code></li>
</ol>
<p>为了优化这两个缺点，下面分成两步来进行</p>
<h3 id="解决写两次的问题"><a href="#解决写两次的问题" class="headerlink" title="解决写两次的问题"></a>解决写两次的问题</h3><h4 id="简单的autorun"><a href="#简单的autorun" class="headerlink" title="简单的autorun"></a>简单的<code>autorun</code></h4><p>通过一个函数体来进行定义依赖的次数的节约，假设我们有一个<code>autorun</code>函数，只要把所有的副作用代码写在里面，就可以达成只写一次的目标，要实现的效果如下</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> a = <span class="number">1</span></span><br><span class="line"><span class="keyword">let</span> b</span><br><span class="line"><span class="keyword">function</span> <span class="title function_">effect</span>(<span class="params"></span>)&#123;</span><br><span class="line">    b = a*<span class="number">3</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="title function_">autorun</span>(effect)</span><br><span class="line">a = <span class="number">2</span></span><br><span class="line"><span class="title function_">effect</span>()</span><br></pre></td></tr></table></figure>

<p>那么这个autorun的写法如下</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">autorun</span>(<span class="params">fn</span>)&#123;</span><br><span class="line">    <span class="title function_">fn</span>()</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="使用Dep将effect函数收集起来"><a href="#使用Dep将effect函数收集起来" class="headerlink" title="使用Dep将effect函数收集起来"></a>使用<code>Dep</code>将<code>effect</code>函数收集起来</h4><p>以上的<code>autorun</code>只能够初始化的时候，帮我们运行一下<code>effect</code>，为了实现下一步的<code>effect</code>自动化触发，我们需要想办法把这个<code>effect</code>函数收集起来，这里就引入了依赖收集的概念，目标是实现<code>Dep</code>以达成以下的操作</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> a = <span class="number">1</span></span><br><span class="line"><span class="keyword">let</span> b</span><br><span class="line"><span class="keyword">let</span> dep = <span class="keyword">new</span> <span class="title class_">Dep</span>()</span><br><span class="line"><span class="title function_">autorun</span>(<span class="function">()=&gt;</span>&#123;</span><br><span class="line">    <span class="comment">// 只要运行这个函数，就能把这个箭头函数作为依赖收集起来</span></span><br><span class="line">    dep.<span class="title function_">depend</span>()</span><br><span class="line">    b = a*<span class="number">3</span></span><br><span class="line">&#125;)</span><br><span class="line">a = <span class="number">2</span></span><br><span class="line">dep.<span class="title function_">notify</span>()</span><br></pre></td></tr></table></figure>

<p>通过调用<code>dep.depend()</code>，能够把自己所处的这个箭头函数作为依赖收集起来，而通过调用<code>dep.notify()</code>，就能够通知副作用的再次运行。</p>
<p>首先考虑非箭头函数的实现方式</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Dep</span>&#123;</span><br><span class="line">    <span class="title function_">constructor</span>(<span class="params"></span>)&#123;</span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">subscribers</span> = <span class="keyword">new</span> <span class="title class_">Set</span>()</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="title function_">depend</span>(<span class="params"></span>)&#123;</span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">subscribers</span>.<span class="title function_">add</span>(effect)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="title function_">notify</span>(<span class="params"></span>)&#123;</span><br><span class="line">        <span class="comment">// 重新运行所有依赖</span></span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">subscribers</span>.<span class="title function_">forEach</span>(<span class="function"><span class="params">sub</span>=&gt;</span><span class="title function_">sub</span>())</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">function</span> <span class="title function_">autorun</span>(<span class="params">fn</span>)&#123;</span><br><span class="line">    <span class="title function_">fn</span>()</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">const</span> dep = <span class="keyword">new</span> <span class="title class_">Dep</span>()</span><br><span class="line"><span class="keyword">let</span> a = <span class="number">1</span></span><br><span class="line"><span class="keyword">let</span> b</span><br><span class="line"><span class="keyword">function</span> <span class="title function_">effect</span>(<span class="params"></span>)&#123;</span><br><span class="line">    dep.<span class="title function_">depend</span>()</span><br><span class="line">    b = a*<span class="number">3</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="title function_">autorun</span>(effect)</span><br><span class="line">a = <span class="number">2</span></span><br><span class="line">dep.<span class="title function_">notify</span>()</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(b) <span class="comment">// 6</span></span><br></pre></td></tr></table></figure>

<p>由于把<code>effect</code>写死在了<code>Dep</code>内，使得这个类仅能适用于<code>effect</code>函数，如果后续有<code>effect2</code>，则无法使用，所以为了使<code>Dep</code>通用化，需要想办法实现类似最初的箭头函数的写法，并且让<code>Dep</code>能够拿到这个箭头函数的运行上下文，使用的技巧就是全局的提取，提取的时机就是在<code>autorun</code>中实际要运行<code>fn</code>前，通过这种方式，我们就可以拿到箭头函数的实例</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> globalFn</span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Dep</span>&#123;</span><br><span class="line">    <span class="title function_">depend</span>(<span class="params"></span>)&#123;</span><br><span class="line">        <span class="comment">// 当副作用是通过dep.notify调用时，globalFn为null因此不会被收集</span></span><br><span class="line">        <span class="keyword">if</span>(globalFn)&#123;</span><br><span class="line">            <span class="variable language_">this</span>.<span class="property">subscribers</span>.<span class="title function_">add</span>(globalFn)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">function</span> <span class="title function_">autorun</span>(<span class="params">fn</span>)&#123;</span><br><span class="line">    globalFn = fn</span><br><span class="line">    <span class="title function_">fn</span>()</span><br><span class="line">    globalFn = <span class="literal">null</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="解决需要手动调用的问题"><a href="#解决需要手动调用的问题" class="headerlink" title="解决需要手动调用的问题"></a>解决需要手动调用的问题</h3><p>通过解决写两次的问题，创建了一个<code>Dep</code>类能够收集起来<code>effect</code>，并且使用<code>depend</code>和<code>notify</code>实现依赖的管理。而最终极的写法是将手动调用Dep的代码也给封装起来，实现以下的调用形式</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> a = <span class="number">1</span></span><br><span class="line"><span class="keyword">let</span> b</span><br><span class="line"><span class="title function_">autorun</span>(<span class="function">()=&gt;</span>&#123;</span><br><span class="line">    b = a*<span class="number">3</span></span><br><span class="line">&#125;)</span><br><span class="line">a = <span class="number">2</span></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(b) <span class="comment">// 6</span></span><br></pre></td></tr></table></figure>

<p>为了使其更漂亮，将变量放在一个<code>state</code>和<code>computed</code>中来使其更类似于<code>Vue</code></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> state = &#123;</span><br><span class="line">    <span class="attr">a</span>:<span class="number">1</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">let</span> computed = &#123;</span><br><span class="line">    <span class="attr">b</span>:<span class="literal">undefined</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="title function_">autorun</span>(<span class="function">()=&gt;</span>&#123;</span><br><span class="line">    computed.<span class="property">b</span> = state.<span class="property">a</span> * <span class="number">3</span></span><br><span class="line">&#125;)</span><br><span class="line">state.<span class="property">a</span> = <span class="number">2</span></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(computed.<span class="property">b</span>) <span class="comment">// 6</span></span><br></pre></td></tr></table></figure>

<p>为了使<code>dep.depend</code>和<code>dep.notify</code>能够被自动调用，通过<code>observe</code>中的<code>getter</code>和<code>setter</code>钩子来勾住这两个调用：在获取变量时，使用<code>depend</code>收集依赖；在设置变量时，使用<code>notify</code>重新计算依赖</p>
<p>简单响应式系统的实现代码如下</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Dep</span>&#123;</span><br><span class="line">    <span class="title function_">constructor</span>(<span class="params"></span>)&#123;</span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">subs</span> = <span class="keyword">new</span> <span class="title class_">Set</span>()</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="title function_">depend</span>(<span class="params"></span>)&#123;</span><br><span class="line">        <span class="keyword">if</span>(globalFn)&#123;</span><br><span class="line">            <span class="variable language_">this</span>.<span class="property">subs</span>.<span class="title function_">add</span>(globalFn)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="title function_">notify</span>(<span class="params"></span>)&#123;</span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">subs</span>.<span class="title function_">forEach</span>(<span class="function"><span class="params">sub</span>=&gt;</span><span class="title function_">sub</span>())</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">let</span> globalFn</span><br><span class="line"><span class="keyword">let</span> dep = <span class="keyword">new</span> <span class="title class_">Dep</span>()</span><br><span class="line"><span class="keyword">function</span> <span class="title function_">observe</span>(<span class="params">obj</span>)&#123;</span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">const</span> key <span class="keyword">in</span> obj)&#123;</span><br><span class="line">        <span class="keyword">let</span> val = obj[key]</span><br><span class="line">        <span class="title class_">Object</span>.<span class="title function_">defineProperty</span>(obj,key,&#123;</span><br><span class="line">            <span class="title function_">get</span>(<span class="params"></span>)&#123;</span><br><span class="line">                dep.<span class="title function_">depend</span>()</span><br><span class="line">                <span class="keyword">return</span> val</span><br><span class="line">            &#125;,</span><br><span class="line">            <span class="title function_">set</span>(<span class="params">newVal</span>)&#123;</span><br><span class="line">                val = newVal</span><br><span class="line">                dep.<span class="title function_">notify</span>()</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">function</span> <span class="title function_">autorun</span>(<span class="params">fn</span>)&#123;</span><br><span class="line">    globalFn = fn</span><br><span class="line">    <span class="title function_">fn</span>()</span><br><span class="line">    globalFn = <span class="literal">null</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>使用的方法则如下</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> state = &#123;</span><br><span class="line">    <span class="attr">a</span>:<span class="number">1</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">let</span> computed = &#123;</span><br><span class="line">    <span class="attr">b</span>:<span class="literal">undefined</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 观察state中的所有变量，使其附上dep钩子</span></span><br><span class="line"><span class="title function_">observe</span>(state)</span><br><span class="line"><span class="title function_">autorun</span>(<span class="function">()=&gt;</span>&#123;</span><br><span class="line">    computed.<span class="property">b</span> = state.<span class="property">a</span> * <span class="number">3</span></span><br><span class="line">&#125;)</span><br><span class="line">state.<span class="property">a</span> = <span class="number">2</span></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(computed.<span class="property">b</span>) <span class="comment">// 6</span></span><br></pre></td></tr></table></figure>

<h3 id="进一步使其更像Vue"><a href="#进一步使其更像Vue" class="headerlink" title="进一步使其更像Vue"></a>进一步使其更像<code>Vue</code></h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">miniVue</span>&#123;</span><br><span class="line">    <span class="title function_">constructor</span>(<span class="params">option</span>)&#123;</span><br><span class="line">        <span class="comment">// 初始化globalFn和dep</span></span><br><span class="line">        <span class="variable language_">this</span>.<span class="title function_">observe</span>(option.<span class="property">data</span>)</span><br><span class="line">        <span class="variable language_">this</span>.<span class="title function_">autoRun</span>(option.<span class="property">computed</span>)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="title function_">autoRun</span>(<span class="params">computed</span>)&#123;</span><br><span class="line">        <span class="comment">// 遍历computed，取出每个函数并运行依赖，</span></span><br><span class="line">        <span class="comment">// 此时dep就会在computed变量和data中架起桥梁，</span></span><br><span class="line">        <span class="comment">// computed依赖于data，而data中的get在调用时正好搭起了dep的桥梁</span></span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">const</span> fnName <span class="keyword">in</span> computed)&#123;</span><br><span class="line">            <span class="variable language_">this</span>.<span class="property">globalFn</span> = computed[fnName]</span><br><span class="line">            computed[fnName]()</span><br><span class="line">            <span class="variable language_">this</span>.<span class="property">globalFn</span> = <span class="literal">null</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="title function_">observe</span>(<span class="params"></span>)&#123;</span><br><span class="line">        <span class="comment">// ...</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/page/tags/Vue/" rel="tag"># Vue</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/page/2021/11/13/%E4%BD%BF%E7%94%A8%E5%AA%92%E4%BD%93api%E5%AE%9E%E7%8E%B0%E7%BD%91%E9%A1%B5%E5%BD%95%E5%B1%8F/" rel="prev" title="使用媒体api实现网页录屏">
                  <i class="fa fa-chevron-left"></i> 使用媒体api实现网页录屏
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/page/2022/05/09/%E5%9C%A8react-navigation%E4%B8%AD%E8%8E%B7%E5%BE%97ts%E6%8F%90%E7%A4%BA/" rel="next" title="在react-navigation中获得ts提示">
                  在react-navigation中获得ts提示 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






    <div class="comments utterances-container"></div>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">爱爱爱呵风他</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script size="300" alpha="0.6" zIndex="-1" src="https://cdn.jsdelivr.net/npm/ribbon.js@1.0.2/dist/ribbon.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/page/js/comments.js"></script><script src="/page/js/utils.js"></script><script src="/page/js/motion.js"></script><script src="/page/js/next-boot.js"></script>

  
<script src="https://cdn.jsdelivr.net/npm/hexo-generator-searchdb@1.4.0/dist/search.js" integrity="sha256-vXZMYLEqsROAXkEw93GGIvaB2ab+QW6w3+1ahD9nXXA=" crossorigin="anonymous"></script>
<script src="/page/js/third-party/search/local-search.js"></script>





  




<script class="next-config" data-name="utterances" type="application/json">{"enable":true,"repo":"assd12138/utterancesComment","issue_term":"pathname","theme":"preferred-color-scheme"}</script>
<script src="/page/js/third-party/comments/utterances.js"></script>

</body>
</html>
